/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.alien.admin.modules.deploy.service.impl;

import com.alien.admin.modules.deploy.domain.DpEnvVariables;
import com.alien.admin.modules.deploy.domain.DpServer;
import com.alien.admin.modules.deploy.repository.DpServerRepository;
import com.alien.admin.modules.system.domain.User;
import com.alien.admin.modules.system.repository.UserRepository;
import com.alien.admin.utils.*;
import lombok.RequiredArgsConstructor;
import com.alien.admin.modules.deploy.repository.DpEnvVariablesRepository;
import com.alien.admin.modules.deploy.service.DpEnvVariablesService;
import com.alien.admin.modules.deploy.service.dto.DpEnvVariablesDto;
import com.alien.admin.modules.deploy.service.dto.DpEnvVariablesQueryCriteria;
import com.alien.admin.modules.deploy.service.mapstruct.DpEnvVariablesMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zengzhifang
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2021-09-15
 **/
@Service
@RequiredArgsConstructor
public class DpEnvVariablesServiceImpl implements DpEnvVariablesService {

    private final DpEnvVariablesRepository dpEnvVariablesRepository;
    private final DpEnvVariablesMapper dpEnvVariablesMapper;
    private final UserRepository userRepository;
    private final DpServerRepository dpServerRepository;

    @Override
    public Map<String, Object> queryAll(DpEnvVariablesQueryCriteria criteria, Pageable pageable) {
        Page<DpEnvVariables> page = dpEnvVariablesRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(dpEnvVariablesMapper::toDto));
    }

    @Override
    public List<DpEnvVariablesDto> queryAll(DpEnvVariablesQueryCriteria criteria) {
        return dpEnvVariablesMapper.toDto(dpEnvVariablesRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public DpEnvVariablesDto findById(Integer id) {
        DpEnvVariables dpEnvVariables = dpEnvVariablesRepository.findById(id).orElseGet(DpEnvVariables::new);
        ValidationUtil.isNull(dpEnvVariables.getId(), "DpEnvVariables", "id", id);
        return dpEnvVariablesMapper.toDto(dpEnvVariables);
    }

    @Override
    @Transactional
    public DpEnvVariablesDto findFirstByProjectIdAndEnvAndName(Integer projectId, String env, String name) {
        DpEnvVariables dpEnvVariables = dpEnvVariablesRepository.findFirstByProjectIdAndEnvAndName(projectId, env, name);
        return dpEnvVariablesMapper.toDto(dpEnvVariables);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DpEnvVariablesDto create(DpEnvVariables resources) {

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername());
        resources.setCreateBy(user.getUsername());
        resources.setUpdateBy(user.getUsername());
        resources.setCreateTime(timestamp);
        resources.setUpdateTime(timestamp);

        if(resources.getProjectId() !=null){
            Optional<DpServer> optional = dpServerRepository.findById(Long.valueOf(resources.getProjectId()));
            if(optional.isPresent()){
                resources.setProjectName(optional.get().getName());
            }
        }

        return dpEnvVariablesMapper.toDto(dpEnvVariablesRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DpEnvVariables resources) {
        DpEnvVariables dpEnvVariables = dpEnvVariablesRepository.findById(resources.getId()).orElseGet(DpEnvVariables::new);
        ValidationUtil.isNull(dpEnvVariables.getId(), "DpEnvVariables", "id", resources.getId());

        User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername());
        resources.setUpdateBy(user.getUsername());
        dpEnvVariables.setUpdateTime(new Timestamp(System.currentTimeMillis()));

        if(resources.getProjectId() !=null){
            Optional<DpServer> optional = dpServerRepository.findById(Long.valueOf(resources.getProjectId()));
            if(optional.isPresent()){
                resources.setProjectName(optional.get().getName());
            }
        }

        dpEnvVariables.copy(resources);
        dpEnvVariablesRepository.save(dpEnvVariables);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            dpEnvVariablesRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<DpEnvVariablesDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DpEnvVariablesDto dpEnvVariables : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("环境", dpEnvVariables.getEnv());
            map.put("0-全局 1-某个服务", dpEnvVariables.getScope());
            map.put("某服务名称，当scope=1时，这个字段有值", dpEnvVariables.getProjectId());
            map.put("变量名称", dpEnvVariables.getName());
            map.put("变量的值", dpEnvVariables.getValue());
            map.put("创建人", dpEnvVariables.getCreateBy());
            map.put("修改人", dpEnvVariables.getUpdateBy());
            map.put("创建日期", dpEnvVariables.getCreateTime());
            map.put("更新时间", dpEnvVariables.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}